<?php
namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Closure;
/**
 * Class ReplayAttacks
 * @package App\Http\Middleware
 * @author zjw
 * 重放攻击控制器
 */
class ReplayAttacks{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle(Request $request, Closure $next){
        $clientTime = $request->timestamp;
        $sign = $request->sign;
        $nonce = $request->nonce;
        if(md5($clientTime . $nonce . "sz") !== $sign){
            throw new InvalidSignatureException();
        }
        $serverTime =  time();
        if($serverTime - $clientTime > 60 ) {
            throw new InvalidSignatureException();
        }
        if(\Cache::get($sign)) {
            throw new InvalidSignatureException();
        }
        \Cache::set($sign,1,60);
        return $next($request);

    }
}
